package com.vb.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vb.entity.SearchResult;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class JsonParseResult {

//    public static List<SearchResult> getListByJSON(String res){
//        List<SearchResult> searchResults = new ArrayList<>();
//        JSONObject jsonObject = JSON.parseObject(res);
//        JSONArray r = jsonObject.getJSONArray("result");
//        for (Object o : r) {
//            JSONObject r2 = (JSONObject) o;
//            JSONObject r3 = JSON.parseObject(r2.toString());
//            String score = r3.get("score").toString();
//            JSONObject r4 = JSON.parseObject(r3.get("brief").toString());
//            String s1 = (String) r4.get("id");
//            String s2 = (String) r4.get("name");
//            SearchResult searchResult = new SearchResult();
//            searchResult.setId(s1);
//            searchResult.setName(s2);
//            searchResult.setScore(new BigDecimal(score));
//            searchResults.add(searchResult);
//        }
//        return searchResults;
//    }

    public static List<SearchResult> getListResult(String res){
        JSONObject jsonObject = JSON.parseObject(res);
        JSONArray r = jsonObject.getJSONArray("result");

        List<SearchResult> searchResults = r.stream()
                .map(o -> (JSONObject) o)
                .map(r2 -> JSON.parseObject(r2.toString()))
                .map(r3 -> {
                    String score = r3.getString("score");
                    JSONObject r4 = JSON.parseObject(r3.getString("brief"));
                    String id = r4.getString("id");
                    String path = r4.getString("path");
                    SearchResult searchResult = new SearchResult();
                    searchResult.setId(id);
                    searchResult.setPath(path);
                    searchResult.setScore(new BigDecimal(score));
                    return searchResult;
                })
                .collect(Collectors.toList());
        return searchResults;
    }
}
